* This file creates Figure D1
* Note: AppD_make_D1_data.do must be run first to create the necessary data inputs

* Merge in the distribution of busyness created in AppD_make_D1_data
use "$saveddata/data_complete_withcosts.dta", clear

set more off

* Predict in-hospital mortality, and create distribution
reghdfe mort, absorb(i.d_age##i.d_male##i.d_ambulance i.d1, savefe)
predict pred_mort, xbd

xtile pred_mort100 = pred_mort, n(100)

* Merge in indicators of predicted busyness
gen hour = arrivalhour
gen date = arrivaldate

merge m:1 hour date site_code using  "$saveddata/panel_census_predictedvalues.dta", keepusing(pred_busy33)

set more off

keep if pred_busy33!=.

cap drop diff_death
	
foreach x in 60 120 180 240 300 360 400 420 480 540 600{
gen dep`x' = 0
replace dep`x'=1 if depdur<=`x' & depdur!=.
}	
	
collapse (mean) dep*, by(pred_busy pred_mort100)

foreach x in 180{
twoway scatter dep`x' pred_mort100 if pred_busy==0, msymbol(o) connect(line) lcolor(black) mcolor(black) || scatter dep`x' pred_mort100 if pred_busy==1, msymbol(o) connect(line) lcolor(red) mcolor(red) ///
xtick(0(20)100)  graphregion(color(white)) ///
	legend(lab(1 "Non-busy") lab(2 "Busy") order(1 2)) ///
	ytitle("Proportion exiting within 180 minutes") xtit("Percentiles of predicted mortality")
	graph export "$results/FigD1.pdf", as(pdf) replace
}



* Alternative presentations of these graphs (looking at different metrics of exits - mean wait times, and the distribution at different wait periods)
************************************************************************************************************************************************************************

twoway scatter depdur pred_mort100 if pred_busy==0, msymbol(o) connect(line) lcolor(black) mcolor(black) || scatter depdur pred_mort100 if pred_busy==1, msymbol(o) connect(line) lcolor(red) mcolor(red) ///
xtick(0(20)100)  graphregion(color(white)) ///
	legend(lab(1 "Non-busy") lab(2 "Busy") order(1 2)) ///
	ytitle("Mean waiting time (minutes)") xtit("Percentiles of predicted mortality")
	graph export "$results/predmort_waits_expectations.pdf", as(pdf) replace		


	* NOTE: 180 = FIGURE D1
foreach x in 60 120 180 240 300 360 400 420 480 540 600{
twoway scatter dep`x' pred_mort100 if pred_busy==0, msymbol(o) connect(line) lcolor(black) mcolor(black) || scatter dep`x' pred_mort100 if pred_busy==1, msymbol(o) connect(line) lcolor(red) mcolor(red) ///
xtick(0(20)100)  graphregion(color(white)) ///
	legend(lab(1 "Non-busy") lab(2 "Busy") order(1 2)) ///
	ytitle("Proportion exiting within `x' minutes") xtit("Percentiles of predicted mortality")
	graph export "$results/predmort_waits`x'_expectations.pdf", as(pdf) replace
}
